package com.zenithmind.chat.service.impl;

import com.zenithmind.chat.pojo.entity.AiChat;
import com.zenithmind.chat.service.AiChatPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * AI对话权限服务实现类
 * 遵循单一职责原则，专门负责权限验证逻辑
 */
@Slf4j
@Service
public class AiChatPermissionServiceImpl implements AiChatPermissionService {
    
    @Override
    public boolean hasPermission(AiChat chat, String userId) {
        if (chat == null || userId == null) {
            return false;
        }
        
        // 检查是否是对话的所有者
        if (userId.equals(chat.getUserId())) {
            return true;
        }
        
        // 检查是否是公开分享的对话
        if (chat.getShareType() != null && chat.getShareType() == 1) {
            return true;
        }
        
        // 检查是否在指定分享用户列表中
        if (chat.getShareType() != null && chat.getShareType() == 2 && 
            chat.getSharedUserIds() != null) {
            String[] sharedUserIds = chat.getSharedUserIds().split(",");
            for (String sharedUserId : sharedUserIds) {
                if (userId.equals(sharedUserId.trim())) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    @Override
    public boolean hasModifyPermission(AiChat chat, String userId) {
        if (chat == null || userId == null) {
            return false;
        }
        
        // 只有对话的所有者才能修改
        return userId.equals(chat.getUserId());
    }
    
    @Override
    public boolean hasDeletePermission(AiChat chat, String userId) {
        if (chat == null || userId == null) {
            return false;
        }
        
        // 只有对话的所有者才能删除
        return userId.equals(chat.getUserId());
    }
    
    @Override
    public void checkPermission(AiChat chat, String userId) throws SecurityException {
        if (!hasPermission(chat, userId)) {
            log.warn("用户 {} 尝试访问无权限的对话 {}", userId, chat != null ? chat.getId() : "null");
            throw new SecurityException("无权限访问该对话");
        }
    }
}
